package com.rabbitmq.ChattingRoom.controller.biz;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.ChattingRoom.config.RedisUtilTemplate;
import com.rabbitmq.ChattingRoom.service.UserService;
import com.rabbitmq.ChattingRoom.util.Entity.User;
import com.rabbitmq.ChattingRoom.util.common.base.Result;
import com.rabbitmq.ChattingRoom.util.common.enums.RedisTTLEnum;
import com.rabbitmq.ChattingRoom.util.common.req.*;
import com.rabbitmq.ChattingRoom.util.common.resp.UserLoginRESP;
import com.rabbitmq.ChattingRoom.util.common.resp.UserRESP;
import com.rabbitmq.ChattingRoom.util.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

@Component
public class UserBiz {

    @Autowired
    UserService userService;

    private RedisUtilTemplate redisUtilTemplate = new RedisUtilTemplate();

    public Result<String> Register(UserRegisterReq req) {
        if (!ObjectUtils.isEmpty(userService.selectUserByName(req.getUsername()))) {
            return Result.error("当前账户已被注册!");
        }

        if (userService.register(req) > 0) {
            return Result.success("注册成功!");
        }
        return Result.error("注册失败!");
    }

    public Result<UserLoginRESP> login(UserLoginReq req) {
        User user = userService.selectUserByName(req.getUsername());
        // 登录成功
        if (user.getPassword().equals(MD5Util.encrypt(req.getPassword(), user.getSalt()))) {
            // 将用户信息存入redis、生成token
            String token = TokenUtils.token(user.getId(), user.getUsername(), user.getPassword());
            redisUtilTemplate.set(token, "1", RedisTTLEnum.REDIS_TTL_TOKEN_ENUM.getTime());    // token有限时间 默认 3分钟
            redisUtilTemplate.set("user_" + user.getId().toString(), JSONObject.toJSONString(user), RedisTTLEnum.REDIS_TTL_USER_ENUM.getTime());
            UserLoginRESP userLoginRESP = new UserLoginRESP();
            userLoginRESP = BeanUtil.copyProperties(user, UserLoginRESP.class);
            userLoginRESP.setToken(token);
            return Result.success("登录成功!", userLoginRESP);
        }
        // 登录失败
        return Result.error("用户名或密码错误!");
    }

    public Result<String> keepAlive(String token) {
        // 判断token是否存在
        if (redisUtilTemplate.hasKey(token)) {
            // 通过token获取userid
            Long id = TokenUtils.getId(token);
            redisUtilTemplate.expire("user_" + id.toString(), RedisTTLEnum.REDIS_TTL_USER_ENUM.getTime());
            return Result.success("心跳更新成功!");
        }
        return Result.error("token不存在或已失效!");
    }

    public Result<String> logoff(UserLogoffReq req) {
        redisUtilTemplate.del(req.getToken());
        return Result.success("退出成功!");
    }

    public Result<List<UserRESP>> getUserAliveCount(String token) {
        List<String> userStrList = redisUtilTemplate.redisScanStartValues("user_");
        List<UserRESP> userList = new ArrayList<>();
        for (String userStr : userStrList) {
            System.err.println("userList: " + userStrList);
            System.err.println("id: " + TokenUtils.getId(token));
            System.err.println("userStr: " + userStr);
            if (userStr.contains(TokenUtils.getId(token).toString())) {
                userList.add(JSONUtil.parse(userStr, UserRESP.class));
            }
        }
        return Result.success("获取成功!", userList);
    }

    public Result<List<UserRESP>> getUsers() {
        return Result.success("获取成功！", userService.getUsers());
    }

    public Result<UserRESP> getUserInfo(String token) {
        Long userId = TokenUtils.getId(token);
        User user = userService.selectUserById(userId);
        UserRESP userRESP = BeanUtil.copyProperties(user, UserRESP.class);
        return Result.success("获取成功!", userRESP);
    }

    public Result<String> updatePwd(UpdateUserReq req) {
        User user = BeanUtil.copyProperties(req,User.class);
        if (!ObjectUtils.isEmpty(req.getPassword())) {
            String salt = StringUtil.saltGenerator(5);
            user.setSalt(salt).setPassword(MD5Util.encrypt(req.getPassword(),salt));
        }
        System.err.println(req);
        System.err.println(user);
        int flag = userService.UpdateUser(user);
        if (flag > 0) {
            return Result.success("成功!");
        } else {
            return Result.error("失败！");
        }
    }

}
